define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        Monkey = require("./monkey"),
        config = app.config,
        method = app.method;
        require("./jq_pagination");    
        require("./selectgoods");    

        if($("#select-commodity").length){  
            var $list_template = require("./temp/list_template.html"),
                $js_template = require("./temp/js_template.html"),
                $all_template = require("./temp/all_template.html");

            var SelecteFun = function(opts) {
                this.selectObj = {};
                //this.selectedArray = JSON.parse($("#beenSelected").val());

                if($("#beenSelected").val().length){
                    this.selectedArray = $("#beenSelected").val().split(",");
                }else{
                    this.selectedArray = [];
                }

                if($("#bennName").val().length){
                    this.selectedName = $("#bennName").val().split(",");
                }else{
                    this.selectedName = [];
                }
                this.selectObj.weiFans = this.selectedArray;
                this.selectObj.wName = this.selectedName;
                this.methodType = $("#append-wei").data("methodType");
                this.pageIndex = 0;
                this.globalBoll = true;
                this.num = $("span.select-num").html();
                this.oldNum = [];
                this.maxSize = 5;
                this.opts = $.extend(true,{
                    firstUrl:"/Plus/prefer1.php",
                    partUrl:"/Plus/prefer.php",
                    listUrl:""
                },opts||{});
                this.init();
            }

            SelecteFun.prototype = {
                init:function(){
                    var _this = this,
                        html = template.compile($js_template);
                    _this.create({});
                    _this._click();
                    //_this.isAjax();
                    _this.searchF();
                    _this.saveD();
                    _this.hide();
                    $("#append-wei").append(html(this.selectObj));
                    $("#select-commodity").on("click",function(){
                        $("#js_question_modal").modal("show");
                        _this.globalBoll = true;
                        _this.removeObj(true);
                    });

                    $("#append-wei").on("click",".search-choice-close",function(){
                        var $cid = $(this).closest(".search-choice").data("cid"),
                            $box = $(this).closest(".search-choice"),
                            $path = $("#append-wei").data("path");
                        
                        $box.fadeOut(function() {
                            if($path){
                                Monkey.post($path,function(d){
                                    if(d.status == 0){
                                        $box.remove();
                                        config.msg.suc(d.message || config.lang.removeSuccess, d.url);
                                    }
                                },'',null,{cid:$cid})
                            }else{
                               $box.remove(); 
                            }

                            for(var i=0;i<_this.selectedArray.length;i++){
                                if(_this.selectedArray[i] == $cid){
                                    _this.selectedArray.splice(i,1);
                                    _this.selectedName.splice(i,1);
                                }
                            }
                            
                            //$("#beenSelected").val("["+_this.selectedArray+"]");

                            $("#beenSelected").val(_this.selectedArray);
                            $("#bennName").val(_this.selectedName);

                            if(_this.methodType){
                                if(_this.selectedArray.length <= 0){
                                    $("#select-commodity").removeClass("hide");
                                }
                            }

                        });
                    });

                    if(_this.methodType){
                        if(_this.selectedArray.length){
                            $("#select-commodity").addClass("hide");
                        }else{
                            $("#select-commodity").removeClass("hide");
                        }
                    }
                },
                create:function(searchData){
                    var _this = this;
                    Monkey.post(_this.opts.firstUrl,function(d){
                        if(d){
                            var $html = template.compile($all_template);
                            $('#all-list-box').append($html(d));
                            /*var dHtml = '<div class="list-box" data-crate=false><ul></ul></div>';
                            for(var i=1;i<d.numberPages;i++){
                               $('#all-list-box').append(dHtml);
                            }*/
                            var initPagination = function() {
                                // 创建分页
                                $("#Pagination").pagination(d.numberPages, {
                                    num_edge_entries: 1, //边缘页数
                                    num_display_entries: 4, //主体页数
                                    callback: pageselectCallback,
                                    items_per_page: 1, //每页显示1项
                                    prev_text: "&laquo",
                                    next_text: "&raquo",
                                    load_first_page: true //第一次自动加载,true(默认),false(不加载)
                                });
                             };

                            var pageselectCallback = function(page_index, jq){
                                //_this.pageIndex = page_index;
                                $('#all-list-box div.list-box').hide();

                                if(!$('#all-list-box div.list-box:eq(' + page_index + ')').data("crate")){
                                    var data = $("#commodity-box").serialize();
                                    data += "&page=" + (page_index+1) + "";
                                    Monkey.post(_this.opts.listUrl,function(datas){
                                        var _html = template.compile($list_template);
                                        $('#all-list-box').empty();
                                        $('#all-list-box').append(_html(datas));
                                        _this.removeObj(false);
                                        //$('#all-list-box div.list-box:eq(' + page_index + ')').append(_html(datas));
                                        //$('#all-list-box div.list-box:eq(' + page_index + ')').data("crate",true);
                                    },'',null,data)
                                }
                                
                                $('#all-list-box div.list-box:eq(' + page_index + ')').show();
                                
                                //阻止单击事件
                                return false;
                            }

                            initPagination();
                        }

                    },'',null,searchData);
                },
                _click:function(){
                    var _this = this;
                    $(document).on("click","li.itmes",function(){
                        var cid = $(this).data("cid");
                        var wName = $(this).data("name");
                        var activeItme = $(this).find("a");
                            

                        if(_this.methodType){
                            $(this).siblings("li.itmes").removeClass("active");
                            $(this).siblings("li.itmes").find("a").removeClass("active");

                            activeItme.toggleClass("active");
                            $(this).toggleClass("active");

                            _this.selectedArray = [];
                            _this.selectedName = [];

                            if($(this).hasClass("active")){
                                _this.selectedArray.push(cid);
                                _this.selectedName.push(wName);
                            }else{
                                _this.selectedArray = [];
                                _this.selectedName = [];
                            }

                        }else{

                            if(_this.selectedArray.length >= _this.maxSize){
                                
                                if($(this).hasClass("active")){
                                    activeItme.removeClass('active');
                                    $(this).removeClass('active');
                                    for(var i=0;i<_this.selectedArray.length;i++){
                                        if(_this.selectedArray[i] == cid){
                                            _this.selectedArray.splice(i,1);
                                            _this.selectedName.splice(i,1);
                                        }
                                    }
                                }else{
                                    config.msg.error("最多添加{0}个".format(_this.maxSize));
                                }
                                return;
                            }


                            activeItme.toggleClass("active");
                            $(this).toggleClass("active");

                            if($(this).hasClass("active")){
                                _this.selectedArray.push(cid);
                                _this.selectedName.push(wName);
                                _this.animateF($(".fly-num"),true);
                            }else{
                                for(var i=0;i<_this.selectedArray.length;i++){
                                    if(_this.selectedArray[i] == cid){
                                        _this.selectedArray.splice(i,1);
                                        _this.selectedName.splice(i,1);
                                    }
                                }
                                _this.animateF($(".fly-num"),false);
                            }
                                
                            if(_this.oldNum.length != _this.selectedArray.length){
                                $("a.select-box").data("ajax",false);
                            }else{
                                 if(_this.oldNum.sort().toString() == _this.selectedArray.sort().toString()){
                                    $("a.select-box").data("ajax",true);
                                }else{
                                    $("a.select-box").data("ajax",false);
                                }
                            }
                            $("span.select-num").html(_this.selectedArray.length);
                        }
                    })
                },
                isAjax:function(){
                    var _this = this;
                    $(document).on("click","#myTab a.select-box",function(){
                        var $this = $(this);
                        if($this.data("ajax")){return}
                        Monkey.post(_this.opts.partUrl,function(d){
                            if(d){
                                $this.data("ajax","true");
                                $("span.select-num").html(d.select);
                                $("#beenSelected").val(_this.selectedArray);
                                //_this.oldNum = JSON.parse("["+$("#beenSelected").val()+"]");
                                _this.oldNum = JSON.parse($("#beenSelected").val());
                                var $html = template("js_template",d);
                                //$("#hiddenresult").empty().append($html);
                                //var length = $("#hiddenresult li").length;

                                $("#Searchresult").empty().append($html);
                                var length = $("#Searchresult li").length;

                                var initPagination = function() {
                                    var num_entries = $("#Searchresult li").length;
                                    // 创建分页
                                    $("#Pagination1").pagination(num_entries, {
                                        num_edge_entries: 1, //边缘页数
                                        num_display_entries: 4, //主体页数
                                        callback: pageselectCallback,
                                        items_per_page: 5, //每页显示1项
                                        prev_text: "&laquo",
                                        next_text: "&raquo"
                                    });
                                 };

                                var pageselectCallback = function(page_index, jq){

                                    //注视的代码是 清空的方法
                                    var items_per_page = 5;
                                    var max_elem = Math.min((page_index+1) * items_per_page, length);
                                    //$("#Searchresult").html("");
                                    $('#Searchresult li').addClass("hide");
                                    // 获取加载元素
                                    for(var i=page_index*items_per_page;i<max_elem;i++){
                                        //$("#Searchresult").append($("#hiddenresult li:eq("+i+")").clone());
                                        $('#Searchresult li:eq(' + i + ')').removeClass("hide"); 
                                    }
                                    //阻止单击事件
                                    return false;
                                }
                                initPagination();
                            }
                        },"div.tab-content",null,{select:_this.selectedArray});
                    })
                },
                searchF:function(){
                    var _this = this;
                    $(document).on("click","#search",function(){
                        $("#all-list-box").empty();
                        _this.create($("#commodity-box").serialize());
                    })
                },
                animateF:function(obj,bools){
                    var _this = this;
                    var $html = "";
                    if(bools){
                        $html = "+1";
                    }else{
                        $html = "-1"
                    }
                    $(".fly-num").html($html).css("display","block").stop().animate({
                        "top":"-25px",
                        "right":"15px",
                        "opacity":0,
                        "fontSize":"14px"
                    },600,function(){
                        $(this).css({"top":"-5px","right":"25px","display":"none","opacity":1,"font-size":"10px"});
                    });
                },
                saveD:function(){
                    var _this = this;
                    $(document).on("click","#saveData",function(){
                        var weiFans = [],
                            obj = {},
                            $path = $(this).data("path");
                        var html = template.compile($js_template);

                        //$("#beenSelected").val("["+_this.selectedArray+"]");

                        $("#beenSelected").val(_this.selectedArray);
                        $("#bennName").val(_this.selectedName);

                        _this.selectObj.weiFans = _this.selectedArray;
                        _this.selectObj.wName = _this.selectedName;

                        if($path){
                            Monkey.post($path,function(d){
                                if(d.status == 0){
                                    $("#choose-ul").remove();
                                    $("#append-wei").append(html(_this.selectObj));
                                    config.msg.suc(d.message || config.lang.removeSuccess, d.url);
                                }else{
                                    config.msg.suc(d.message || config.lang.removeSuccess, d.url);
                                }
                            },'',null,{cid:_this.selectedArray.toString()})
                        }else{
                            $("#choose-ul").remove();
                            $("#append-wei").append(html(_this.selectObj));
                        }

                        if(_this.methodType){
                            if(_this.selectedArray.length){
                                $("#select-commodity").addClass("hide");
                            }
                        }

                        _this.globalBoll = false;

                    });
                },
                hide:function(){
                    var _this = this;
                    $('#js_question_modal').on('hidden.bs.modal', function (e) {
                        _this.globalBoll && _this.removeObj(true);
                    })
                },
                removeObj:function(bolg){
                    var _this = this;
                    var selectedCid = [];
                    if(bolg){
                        if($("#beenSelected").val().length){
                            selectedCid = $("#beenSelected").val().split(",");
                        }else{
                            selectedCid = [];
                        }
                    }else{
                        selectedCid = _this.selectedArray;
                    }

                    $('#all-list-box div.list-box:eq(' + _this.pageIndex + ')').find("li.itmes").each(function(){
                        $(this).removeClass("active");
                        $(this).find("a").removeClass("active");
                        for(var k=0;k<selectedCid.length;k++){
                            if(selectedCid[k] == $(this).data("cid")){
                                $(this).addClass("active");
                                $(this).find("a").addClass("active");
                            }
                        }
                    });

                    if(bolg){
                        if($("#beenSelected").val().length){
                            this.selectedArray = $("#beenSelected").val().split(",");
                        }else{
                            this.selectedArray = [];
                        }

                        if($("#bennName").val().length){
                            _this.selectedName = $("#bennName").val().split(",");
                        }else{
                            _this.selectedName = [];
                        }
                    }
                    
                }
            }

            if(window.config){
                new SelecteFun({
                    firstUrl:window.config.firstdata,
                    listUrl:window.config.listdata
                });
            }
        }
});